package com.flashmoment.video.controller;

import com.flashmoment.video.service.SendMailService;
import com.flashmoment.video.service.UserService;
import com.flashmoment.video.utils.Constant;
import com.flashmoment.video.utils.R;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * @Title: SendMailController
 * @Author xulu
 * @Package com.xulu.mail.controller
 * @Date 2023/6/20 21:46
 */
@RestController
@CrossOrigin
@RequestMapping("video/user")
@Api(tags = "发送验证码接口")
public class SendMailController {


    @Autowired
    private SendMailService sendMailService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserService userService;

    @PostMapping("/sendCode")
    public R sendMail(@RequestBody Map<String, Object> map) {
        //注册或修改密码
        String email = (String) map.get("email");
        String username = (String) map.get("username");
        //登录
        String emailNumber = (String) map.get("emailNumber");
        //修改密码
        //判断用户是否已经注册
        try {
            if (StringUtils.isNotBlank(email) && userService.findUserCount(email) >0 && !StringUtils.isBlank(username)) {
                return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.USER_EXIST);
                //判断用户是否未注册
            } else if( StringUtils.isNotBlank(email) ){
                sendMailService.sendMailService(email);
            }

            if (StringUtils.isNotBlank(emailNumber) && userService.findUserCount(emailNumber)<1) {
                return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.USER_NOT_EXIST);
            } else if (StringUtils.isNotBlank(emailNumber)){
                sendMailService.sendMailService(emailNumber);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Objects.requireNonNull(R.ok().put("code", Constant.FAILURE_CODE)).put("message", Constant.SEND_CODE_FAILURE);

        }
        return Objects.requireNonNull(R.ok().put("code", Constant.SUCCESS_CODE)).put("message", Constant.SEND_CODE_SUCCESS);


    }


}
